package uestc.lj.gulishop.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import uestc.lj.common.constant.WareConstant;
import uestc.lj.common.utils.PageUtils;
import uestc.lj.common.utils.Query;
import uestc.lj.gulishop.ware.dao.PurchaseDao;
import uestc.lj.gulishop.ware.entity.PurchaseDetailEntity;
import uestc.lj.gulishop.ware.entity.PurchaseEntity;
import uestc.lj.gulishop.ware.service.PurchaseDetailService;
import uestc.lj.gulishop.ware.service.PurchaseService;
import uestc.lj.gulishop.ware.service.WareSkuService;
import uestc.lj.gulishop.ware.vo.MergeVO;
import uestc.lj.gulishop.ware.vo.PurchaseDoneVO;
import uestc.lj.gulishop.ware.vo.PurchaseItemDoneVO;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;

    @Autowired
    private WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(params.get("key"))) {
            wrapper.like("assignee_name", params.get("key"));
        }

        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceivePurchase(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("status", 0).or().eq("status", 1);

        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params), wrapper);
        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void mergePurchase(MergeVO mergeVO) {
        // 1.判断是否填写purchaseId
        Long purchaseId = mergeVO.getPurchaseId();
        // 2.未填写需要新建采购单
        if (purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        } else {
            //判断采购单的状态，只有未分配和未完成才合并
            PurchaseEntity purchaseEntity = baseMapper.selectById(purchaseId);
            if (WareConstant.PurchaseStatusEnum.RECEIVE.getCode().equals(purchaseEntity.getStatus())
                    || WareConstant.PurchaseStatusEnum.FINISH.getCode().equals(purchaseEntity.getStatus())
                    || WareConstant.PurchaseStatusEnum.HASERROR.getCode().equals(purchaseEntity.getStatus())) {
                try {
                    throw new Exception("采购单状态不对，无法合并");
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
            List<Long> items = mergeVO.getItems();
            Long finalPurchaseId = purchaseId;
            List<PurchaseDetailEntity> purchaseDetailEntities = items.stream().map(i -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(i);
                purchaseDetailEntity.setPurchaseId(finalPurchaseId);
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());


            purchaseDetailService.updateBatchById(purchaseDetailEntities);
            // 更新修改时间
            PurchaseEntity purchaseEntity2 = new PurchaseEntity();
            purchaseEntity2.setId(purchaseId);
            purchaseEntity2.setUpdateTime(new Date());
            this.updateById(purchaseEntity2);
        }
    }

    @Override
    public void received(List<Long> purchaseIds) {
        // 1.采购单只能时已分配状态
        List<PurchaseEntity> purchaseEntities = purchaseIds.stream().map(purchaseId -> {
            PurchaseEntity purchaseEntity = this.getById(purchaseId);
            return purchaseEntity;
        }).filter(item -> WareConstant.PurchaseStatusEnum.ASSIGNED.getCode().equals(item.getStatus()))
                .map(item -> {
                    item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
                    item.setUpdateTime(new Date());
                    return item;
                })
                .collect(Collectors.toList());
        // 2.改变采购单状态
        this.updateBatchById(purchaseEntities);
        // 3.改变采购项状态
        purchaseEntities.forEach(item -> {
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            List<PurchaseDetailEntity> purchaseDetailEntityList = purchaseDetailEntities.stream().map(entity -> {
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                purchaseDetailEntity.setId(entity.getId());
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(purchaseDetailEntityList);
        });

    }

    @Transactional
    @Override
    public void done(PurchaseDoneVO purchaseDoneVO) {
        // 1.改变采购项状态
        Boolean flag = true;
        List<PurchaseItemDoneVO> items = purchaseDoneVO.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = new ArrayList<>();
        for (PurchaseItemDoneVO item : items) {
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            if (WareConstant.PurchaseDetailStatusEnum.FAILED.getCode().equals(item.getStatus())) {
                flag = false;
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FAILED.getCode());
            } else {
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.FINISH.getCode());
                // 3.将采购成功的进行入库
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                wareSkuService.addStock(entity.getSkuId(), entity.getWareId(), entity.getSkuNum());
            }
            purchaseDetailEntity.setId(item.getItemId());
            purchaseDetailEntities.add(purchaseDetailEntity);
        }
        purchaseDetailService.updateBatchById(purchaseDetailEntities);
        // 2.改变采购单状态
        Long id = purchaseDoneVO.getId();
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag ? WareConstant.PurchaseStatusEnum.FINISH.getCode()
                : WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}